package giftmail.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import giftmail.dao.UserMapper;
import giftmail.model.User;
import giftmail.util.Page;

@Service("userService")
@CacheConfig(cacheNames = {"userCache"})
@Transactional
public class UserServiceImpl implements IUserService {
	
	@Autowired
	private UserMapper userMapper;
	
	
	/**
	 * 数据库操作：
	 * 查看User表List
	 * @author demo
	 */
	@Override
	public List<User> findUser() {
		List<User> list = userMapper.findUser();
		return list;
	}
	
	/**
	 * 数据库操作：
	 * 查看User表List分页
	 * @author demo
	 */
	@Override
	public List<User> findUserListByPage(User user, Page page) {
		Map<String,Object> parameter = new HashMap<String,Object>();
		User u = new User();
		
		//判断条件
		if(StringUtils.isNotBlank(user.getName())){
			u.setName(user.getName());
		}
		
		parameter.put("userImpl", u);
		parameter.put("page", page);
		
		List<User> list = userMapper.findUserListByPage(parameter);
		return list;
	}
	
	
	/**
	 * 根据id查询用户
	 * 同时:插入redis
	 */
	@Cacheable(key = "'user:'+#id", unless = "#result == null")
	@Override
	public User getById(int id){
		User user = userMapper.findUserById(id);
		if(user != null){
			return user;
		}
        return null;
	}

	/**
	 * 用户更新
	 * 同时:删除redis
	 */
	@CacheEvict(key = "'user:'+#user.id")
	@Override
	public void update(User user) {
		Integer id = user.getId();
			User selectByPrimaryKey = userMapper.selectByPrimaryKey(id);
			if(selectByPrimaryKey != null){
				selectByPrimaryKey.setName(user.getName());
				selectByPrimaryKey.setPassword(user.getPassword());
			}
			userMapper.update(selectByPrimaryKey);
		
	}
	
	
	
}
